package com.dykj.fireFighting.web.base.dev.controller;

import com.dykj.fireFighting.api.base.bigdata.device.service.IDeviceService;
import com.dykj.fireFighting.api.base.bigdata.device.vo.DeviceVo;
import com.dykj.fireFighting.api.base.dev.entity.vo.FaultVo;
import com.dykj.fireFighting.api.base.dev.entity.vo.FireVo;
import com.dykj.fireFighting.api.base.dev.service.IDevHisService;
import com.dykj.fireFighting.api.base.dev.service.IDevHisWaterService;
import com.dykj.fireFighting.api.base.dev.service.IDevHisZcService;
import com.dykj.fireFighting.api.base.devHisResult.entity.DevHisResult;
import com.dykj.fireFighting.api.base.devHisResult.service.IDevHisResultService;
import com.dykj.fireFighting.api.base.devHisResult.vo.ResultVo;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.maintenance.service.IUrgentMaintenanceService;
import com.dykj.fireFighting.api.base.maintenance.vo.MaintenanceEvaluationVo;
import com.dykj.fireFighting.api.elasticsearch.devHis.entity.EsDevHis;
import com.dykj.fireFighting.api.elasticsearch.devHis.service.EsDevHisService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.exception.BaseException;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import com.sun.org.apache.bcel.internal.genericb.ARRAYLENGTH;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 消防隐患综合分析
 *
 * @Author LIJIANJIE
 * @Date  2021-07-12 15:10:02
 */
@Slf4j
@Api(value = "消防隐患综合分析接口", tags = {"消防隐患综合分析接口"})
@RestController
@RequestMapping("/devHis")
public class DevHisController {

    /**
     * 火警记录
     */
    @DubboReference
    private IDevHisService devHisService;
    /**
     * 电气记录
     */
    @DubboReference
    private IDevHisZcService devHisZcService;
    /**
     * 水警记录
     */
    @DubboReference
    private IDevHisWaterService devHisWaterService;
    /**
     * 单位（监控中心）
     */
    @DubboReference
    private IEnterpriseService enterpriseService;

    /**
     * 设备
     */
    @DubboReference
    private IDeviceService deviceService;

    /**
     * 统计
     */
    @DubboReference
    private IDevHisResultService devHisResultService;

    /**
     * 紧急维保
     */
    @DubboReference
    private IUrgentMaintenanceService urgentMaintenanceService;

    @DubboReference
    private EsDevHisService esDevHisService;

    /**
     * 获取登录用户的单位（监控中心）id
     */
    public Long getEnterpriseId() {
        try {
            Long enterpriseId = ShiroUtil.getUser().getEnterpriseId();
            return enterpriseId;
        }catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("请登录");
        }
    }

    /**
     * 获取单位信息
     */
    public Enterprise getEnterprise() {
        Enterprise enterprise = enterpriseService.getById(getEnterpriseId());
        return enterprise;
    }

    /**
     * 设备使用情况统计 （运转正常数量 和 运转异常数量）
     */
    @AutoLog(value = "设备使用情况统计")
    @ApiOperation(value = "设备使用情况统计", notes = "设备使用情况统计")
    @RequestMapping(value = "/use", method = RequestMethod.GET)
    public CommonResult getDevUse() {
        try {
            Enterprise enterprise = getEnterprise();
            int type = enterprise.getEnterpriseType();
            Map<String, Integer> map = new HashMap<>(8);
            // 社会单位
            if (type == 0) {
                // 总数
                int count = deviceService.countTotal(enterprise.getId()+"");
                // 异常数
                int fault = deviceService.countFault(enterprise.getId() + "");
                int faultRate = Math.round((fault / count) * 100);
                // 封装
                map.put("normalNum", count - fault);
                map.put("faultNum", fault);
                map.put("faultRate", faultRate);
            }
            // 监控中心
            if (type == 2) {
                // 获取所有单位
                List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
                if (lists == null || lists.size() == 0) {
                    return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
                }
                List<String> ids = new ArrayList<>();
                for (Enterprise list : lists ) {
                    ids.add(list.getId() + "");
                }
                // 总数
                int count = deviceService.countCenterTotal(ids);
                // 异常数
                int fault = deviceService.countCenterFault(ids);
                int faultRate = Math.round((fault / count) * 100);
                // 封装
                map.put("normalNum", count - fault);
                map.put("faultNum", fault);
                map.put("faultRate", faultRate);
            }
            return CommonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("监控中心下单位为空");
        }
    }

    /**
     * 故障情况统计
     */
    @AutoLog(value = "故障情况统计")
    @ApiOperation(value = "故障情况统计", notes = "故障情况统计")
    @RequestMapping(value = "/fault", method = RequestMethod.GET)
    public CommonResult getFaultCount() {
        try {
            Enterprise enterprise = getEnterprise();
            int type = enterprise.getEnterpriseType();
            List<DeviceVo> map = new ArrayList<>();
            // 社会单位
            if (type == 0) {
                map = deviceService.selectByUnit(enterprise.getId() + "");
            }
            // 监控中心
            if (type == 2) {
                // 获取所有单位
                List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
                if (lists == null || lists.size() == 0) {
                    return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
                }
                List<String> ids = new ArrayList<>();
                for (Enterprise list : lists ) {
                    ids.add(list.getId() + "");
                }
                map = deviceService.selectByCenter(ids);
            }
            return CommonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("监控中心下单位为空");
        }
    }

    /**
     * 报警数量统计
     */
    @AutoLog(value = "报警数量统计")
    @ApiOperation(value = "报警数量统计", notes = "报警数量统计")
    @RequestMapping(value = "/alarm", method = RequestMethod.GET)
    public CommonResult getAlarmNum() {
        Enterprise enterprise = getEnterprise();
        int type = enterprise.getEnterpriseType();
        HashMap<String, Integer> map = new HashMap<>(10);
        // 社会单位
        if (type == 0) {
            // 火警总数
            int fire = devHisService.getFireNum(enterprise.getId() + "");
            // 电气报警总数
            int electric = devHisZcService.getElectricNum(enterprise.getId() + "");
            // 水报警总数
            int water = devHisWaterService.getWaterNum(enterprise.getId() + "");
            // 本月火警数
            int currentFire = devHisService.getCurrentFireNum(enterprise.getId() + "");
            // 本月电警数
            int currentElectric = devHisZcService.getCurrentEleNum(enterprise.getId() + "");
            // 本月水警数
            int currentWater = devHisWaterService.getCurrentWaterNum(enterprise.getId() + "");
            //本月总数
            int currentNum = currentFire + currentElectric + currentWater;
            // 上月火警数
            int upFire = devHisService.getUpFireNum(enterprise.getId() + "");
            // 上月电警数
            int upElectric = devHisZcService.getUpEleNum(enterprise.getId() + "");
            // 上月水警数
            int upWater = devHisWaterService.getUpWater(enterprise.getId() + "");
            // 上月总数
            int upNum = upFire + upElectric + upWater;
            // 环比增长
            int ChainGrowth = Math.round(((currentNum - upNum) / upNum) * 100);
            // 封装
            map.put("currentNum",currentNum);
            map.put("upNum",upNum);
            map.put("ChainGrowth",ChainGrowth);
            map.put("fireNum",fire);
            map.put("waterNum",water);
            map.put("electricNum",electric);
        }
        // 监控中心
        if (type == 2) {
            // 获取所有单位
            List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            List<String> ids = new ArrayList<>();
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
            // 火警总数
            int fire = devHisService.getCenterFireNum(ids,null,null);
            // 电气报警总数
            int electric = devHisZcService.getCenterEleNum(ids,null,null);
            // 水报警总数
            int water = devHisWaterService.getCenterWaterNum(ids,null,null);
            // 本月火警数
            int currentFire = devHisService.getCenterCurrentFire(ids);
            // 本月电警数
            int currentElectric = devHisZcService.getCenterCurrentEle(ids);
            // 本月水警数
            int currentWater = devHisWaterService.getCenterCurrentWater(ids);
            //本月总数
            int currentNum = currentFire + currentElectric + currentWater;
            // 上月火警数
            int upFire = devHisService.getCenterUpFire(ids);
            // 上月电警数
            int upElectric = devHisZcService.getCenterUpEle(ids);
            // 上月水警数
            int upWater = devHisWaterService.getCenterUpWater(ids);
            // 上月总数
            int upNum = upFire + upElectric + upWater;
            // 环比增长
            int ChainGrowth = Math.round(((currentNum - upNum) / upNum) * 100);
            // 封装 环比增长
            map.put("currentNum",currentNum);
            map.put("upNum",upNum);
            map.put("ChainGrowth",ChainGrowth);
            map.put("fireNum",fire);
            map.put("waterNum",water);
            map.put("electricNum",electric);
        }
        return CommonResult.success(map);
    }
    /**
     * 故障有效恢复率
     */
    @AutoLog(value = "故障有效恢复率")
    @ApiOperation(value = "故障有效恢复率", notes = "故障有效恢复率")
    @RequestMapping(value = "/faultEffectiveRecoveryRate", method = RequestMethod.GET)
    public CommonResult gatFaultEffectiveRecoveryRate(String month) {
        Enterprise enterprise = getEnterprise();
        int type = enterprise.getEnterpriseType();
        List<String> ids=new ArrayList<>();
        if(type==0){//社会单位
            ids.add(enterprise.getId()+"");
        }else if (type==2){//监控中心
            List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
        }
        Map<String,Double> faultEffectiveRecoveryRate = deviceService.faultEffectiveRecoveryRate(ids,month);
        return  CommonResult.success(faultEffectiveRecoveryRate);
    }

    /**
     * 实时信息
     */
    @AutoLog(value = "实时信息")
    @ApiOperation(value = "实时信息", notes = "实时信息")
    @RequestMapping(value = "/realInfo", method = RequestMethod.GET)
    public CommonResult getRealInfo(String beginTime,String endTime) {
        try {
            Enterprise enterprise = getEnterprise();
            // 获取所有单位
            List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            List<String> ids = new ArrayList<>();
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
            String beginTime1 = beginTime + " 00:00:00";
            String endTime1 = endTime + " 23:59:59";
            DevHisResult centerNum = devHisResultService.getCenterNum(ids, beginTime, endTime);
            // 火警总数
            int fire = centerNum.getFireAlarm();
            // 故障总数
            int fault = centerNum.getFault();
            // 预警总数
            int warn = centerNum.getEarlyWarning();
            // 隐患总数
            int danger = urgentMaintenanceService.getCenterNum(ids,beginTime1,endTime1);
            // 联网单位数量
            int unit = lists.size();
            // 已查看火警列表
            //List<FireVo> list = devHisService.getViewedFireList(ids,beginTime1,endTime1);
            PageVo<EsDevHis> esDevHisPageVo = esDevHisService.searchByCenterId(enterprise.getId() + "", "1",beginTime1,endTime1);
            List<EsDevHis> esList = esDevHisPageVo.getList();
            // 封装
            Map<String, Object> map = new HashMap<>(10);
            map.put("fireTotal", fire);
            map.put("faultTotal", fault);
            map.put("warnTotal", warn);
            map.put("dangerTotal", danger);
            map.put("unitTotal", unit);
            map.put("fireList", esList);
            return CommonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("监控中心下社会单位为空");
        }
    }

    /**
     * 隐患总数对比（参数必传）
     */
    @AutoLog(value = "隐患总数对比（参数必传）")
    @ApiOperation(value = "隐患总数对比", notes = "隐患总数对比")
    @RequestMapping(value = "/dangerContrast", method = RequestMethod.GET)
    public CommonResult getDangerTotal(Integer year) {
        try {
            Enterprise enterprise = getEnterprise();
            int type = enterprise.getEnterpriseType();
            HashMap<String, Integer> map = new HashMap<>(8);
            // 社会单位
            if (type == 0) {
                String id = enterprise.getId() + "";
                // 第一季度
                String beginTime1 = year + "-01-01 00:00:00";
                String endTime3 = year + "-03-31 23:59:59";
                int danger1 = urgentMaintenanceService.getUnitNum(id,beginTime1,endTime3);
                // 第二季度
                String beginTime4 = year + "-04-01 00:00:00";
                String endTime6 = year + "-06-30 23:59:59";
                int danger2 = urgentMaintenanceService.getUnitNum(id,beginTime4,endTime6);
                // 第三季度
                String beginTime7 = year + "-07-01 00:00:00";
                String endTime9 = year + "-09-30 23:59:59";
                int danger3 = urgentMaintenanceService.getUnitNum(id,beginTime7,endTime9);
                // 第四季度
                String beginTime10 = year + "-10-01 00:00:00";
                String endTime12 = year + "-12-31 23:59:59";
                int danger4 = urgentMaintenanceService.getUnitNum(id,beginTime10,endTime12);
                map.put("FirstQuarter", danger1);
                map.put("SecondQuarter", danger2);
                map.put("ThirdQuarter", danger3);
                map.put("FourthQuarter", danger4);
            }
            // 监控中心
            if (type == 2) {
                // 获取所有单位
                List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
                if (lists == null || lists.size() == 0) {
                    return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
                }
                List<String> ids = new ArrayList<>();
                for (Enterprise list : lists ) {
                    ids.add(list.getId() + "");
                }
                // 第一季度
                String beginTime1 = year + "-01-01 00:00:00";
                String endTime3 = year + "-03-31 23:59:59";
                int danger1 = urgentMaintenanceService.getCenterNum(ids,beginTime1,endTime3);
                // 第二季度
                String beginTime4 = year + "-04-01 00:00:00";
                String endTime6 = year + "-06-30 23:59:59";
                int danger2 = urgentMaintenanceService.getCenterNum(ids,beginTime4,endTime6);
                // 第三季度
                String beginTime7 = year + "-07-01 00:00:00";
                String endTime9 = year + "-09-30 23:59:59";
                int danger3 = urgentMaintenanceService.getCenterNum(ids,beginTime7,endTime9);
                // 第四季度
                String beginTime10 = year + "-10-01 00:00:00";
                String endTime12 = year + "-12-31 23:59:59";
                int danger4 = urgentMaintenanceService.getCenterNum(ids,beginTime10,endTime12);
                map.put("FirstQuarter", danger1);
                map.put("SecondQuarter", danger2);
                map.put("ThirdQuarter", danger3);
                map.put("FourthQuarter", danger4);
            }
            return CommonResult.success(map);
        }catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("监控中心下社会单位为空");
        }
    }

    /**
     * 故障总数对比（参数必传）
     * @param beginTime
     * @param endTime
     * @return
     */
    @AutoLog(value = "故障总数对比（参数必传）")
    @ApiOperation(value = "故障总数对比", notes = "故障总数对比")
    @RequestMapping(value = "/faultContrast", method = RequestMethod.GET)
    public CommonResult getFaulttotal(String beginTime,String endTime) {
        Enterprise enterprise = getEnterprise();
        int type = enterprise.getEnterpriseType();
        HashMap<String, Object> map = new HashMap<>(10);
        // 获取上周起始日期
        Map<String, String> lastTime = DateUtil.getLastTime(beginTime);
        String lastBeginDate = lastTime.get("lastBeginDate");
        String lastEndDate = lastTime.get("lastEndDate");
        if (type == 0) {
            String id = enterprise.getId() + "";
            List<String> ids = new ArrayList<>();
            ids.add(id);
            // 本周
            List<FaultVo> list1 = devHisResultService.getFaultList(ids, beginTime, endTime);
            //上周
            List<FaultVo> list2 = devHisResultService.getFaultList(ids,lastBeginDate,lastEndDate);
            // 本周前5和后5
            if (ids.size() > 5 && list1.size() > 5 && list2.size() > 5) {
                List<FaultVo> thisTop = list1.subList(0, 5);
                List<FaultVo> thisAfter = list1.subList(list1.size() - 5, list1.size());
                List<FaultVo> lastTop = list2.subList(0, 5);
                List<FaultVo> lastAfter = list2.subList(list2.size() - 5, list2.size());
                map.put("thisWeekTop5",thisTop);
                map.put("thisWeekAfter5",thisAfter);
                map.put("lastWeekTop5",lastTop);
                map.put("lastWeekAfter5",lastAfter);
            }else {
                map.put("thisWeekTop5",list1);
                map.put("thisWeekAfter5",list1);
                map.put("lastWeekTop5", list2);
                map.put("lastWeekAfter5",list2);
            }
            // 对比
            for (FaultVo list : list1) {
                for (FaultVo last : list2) {
                    if (list.getUnitName().equals(last.getUnitName())) {
                        list.setZjNum(list.getFaultNum() - last.getFaultNum());
                        // 除数不能为0
                        if (last.getFaultNum() == 0) {
                            list.setZjPercentage(list.getFaultNum());
                        }else {
                            list.setZjPercentage(Math.round(((list.getFaultNum() - last.getFaultNum())/ last.getFaultNum()) * 100));
                        }
                    }
                }
            }
            map.put("thisWeekContrast",list1);
            map.put("lastWeekContrast",list2);
        }
        if (type == 2) {
            // 获取所有单位
            List<Enterprise> lists = enterpriseService.queryUnitSelect(getEnterprise().getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            List<String> ids = new ArrayList<>();
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
            // 本周
            List<FaultVo> list1 = devHisResultService.getFaultList(ids, beginTime, endTime);
            // 上周
            List<FaultVo> list2 = devHisResultService.getFaultList(ids,lastBeginDate,lastEndDate);
            // 本周前5和后5
            if (ids.size() > 5 && list1.size() > 5 && list2.size() > 5) {
                List<FaultVo> thisTop = list1.subList(0, 5);
                List<FaultVo> thisAfter = list1.subList(list1.size() - 5, list1.size());
                List<FaultVo> lastTop = list2.subList(0, 5);
                List<FaultVo> lastAfter = list2.subList(list2.size() - 5, list2.size());
                map.put("thisWeekTop5",thisTop);
                map.put("thisWeekAfter5",thisAfter);
                map.put("lastWeekTop5",lastTop);
                map.put("lastWeekAfter5",lastAfter);
            }else {
                map.put("thisWeekTop5",list1);
                map.put("thisWeekAfter5",list1);
                map.put("lastWeekTop5", list2);
                map.put("lastWeekAfter5",list2);
            }
            // 对比
            for (FaultVo list : list1) {
                for (FaultVo last : list2) {
                    if (list.getUnitName().equals(last.getUnitName())) {
                        list.setZjNum(list.getFaultNum() - last.getFaultNum());
                        // 除数不能为0
                        if (last.getFaultNum() == 0) {
                            list.setZjPercentage(list.getFaultNum());
                        }else {
                            list.setZjPercentage(Math.round(((list.getFaultNum() - last.getFaultNum())/ last.getFaultNum()) * 100));
                        }
                    }
                }
            }
            map.put("thisWeekContrast",list1);
            map.put("lastWeekContrast",list2);
        }
        return CommonResult.success(map);
    }

    /**
     * 社会单位报警数量（警情分析）
     */
    @AutoLog(value = "社会单位报警数量")
    @ApiOperation(value = "社会单位报警数量", notes = "社会单位报警数量")
    @RequestMapping(value = "/dateFire", method = RequestMethod.GET)
    public CommonResult getFireByDate(String beginTime, String endTime, int type, String unitId) {
        Enterprise enterprise = getEnterprise();
        // 默认
        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(unitId)) {
            String today = DateUtil.getToday();
            String year = today.substring(0, 4);
            String month = today.substring(5, 7);
            String day = today.substring(8);
            int d = Integer.parseInt(day);
            // 获取所有单位
            List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            List<String> ids = new ArrayList<>();
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
            List<ResultVo> resultVos = new ArrayList<>();
            for (int i = 1; i <= d; i++) {
                ResultVo resultVo = new ResultVo();
                String date = "";
                if (i < 10) {
                    date = year + "-" + month + "-0" + i;
                }
                else {
                    date = year + "-" + month + "-" + i;
                }
                DevHisResult centerNum = devHisResultService.getCenterNum(ids, date, date);
                resultVo.setDate(date);
                resultVo.setNum(centerNum.getFireAlarm());
                resultVos.add(resultVo);
            }
            return CommonResult.success(resultVos);

        }
        // 必须选择俩时间
        else if (StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime)) {
            return CommonResult.failed("请正确选择起始日期");
        }else if (StringUtils.isBlank(unitId) && (StringUtils.isNotBlank(beginTime) || StringUtils.isNotBlank(endTime))) {
            return CommonResult.failed("请选择单位");
        }
        // 某个单位的对比
        else {
            // 日
            if (type == 1) {
                List<ResultVo> list = new ArrayList<>();
                List<ResultVo> unitDate = devHisResultService.getUnitDate(enterprise.getId() + "", unitId, beginTime, endTime);
                List<String> daysBetweenDate = DateUtil.getDaysBetweenDate(beginTime, endTime);
                for (String day : daysBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    list.add(resultVo);
                }
                for (ResultVo unit : unitDate) {
                    for (ResultVo li : list) {
                        if (unit.getDate().equals(li.getDate())) {
                            li.setNum(unit.getNum());
                        }
                    }
                }
                return CommonResult.success(list);
            }
            // 月
            else if (type == 2) {
                List<ResultVo> list = new ArrayList<>();
                List<ResultVo> unitDate = devHisResultService.getMonthDate(unitId,beginTime,endTime);
                List<String> monthBetweenDate = DateUtil.getMonthBetweenDate(beginTime, endTime);
                for (String mon : monthBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(mon);
                    resultVo.setNum(0);
                    list.add(resultVo);
                }
                for (ResultVo unit : unitDate) {
                    for (ResultVo li : list) {
                        if (unit.getDate().equals(li.getDate())) {
                            li.setNum(unit.getNum());
                        }
                    }
                }
                return CommonResult.success(list);
            }
            // 季
            else if (type == 3) {
                List<ResultVo> list = new ArrayList<>();
                List<ResultVo> unitDate = devHisResultService.getQuarterDate(unitId,beginTime,endTime);
                List<String> quarterBetweenDate = DateUtil.getQuarterBetweenDate(beginTime, endTime);
                for (String mon : quarterBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(mon);
                    resultVo.setNum(0);
                    list.add(resultVo);
                }
                for (ResultVo unit : unitDate) {
                    for (ResultVo li : list) {
                        if (unit.getDate().equals(li.getDate())) {
                            li.setNum(unit.getNum());
                        }
                    }
                }
                return CommonResult.success(list);
            }
            // 年
            else {
                List<ResultVo> list = new ArrayList<>();
                List<ResultVo> unitDate = devHisResultService.getYearDate(unitId,beginTime,endTime);
                List<String> yearBetweenDate = DateUtil.getYearBetweenDate(beginTime, endTime);
                for (String mon : yearBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(mon);
                    resultVo.setNum(0);
                    list.add(resultVo);
                }
                for (ResultVo unit : unitDate) {
                    for (ResultVo li : list) {
                        if (unit.getDate().equals(li.getDate())) {
                            li.setNum(unit.getNum());
                        }
                    }
                }
                return CommonResult.success(list);
            }
        }
    }

    /**
     * 隱患分析
     */
    @AutoLog(value = "隱患分析")
    @ApiOperation(value = "隱患分析", notes = "隱患分析")
    @RequestMapping(value = "/danger", method = RequestMethod.GET)
    public CommonResult getDanger() {
        Enterprise enterprise = getEnterprise();
        // 获取所有单位
        List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
        if (lists == null || lists.size() == 0) {
            return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
        }
        List<String> ids = new ArrayList<>();
        for (Enterprise list : lists ) {
            ids.add(list.getId() + "");
        }
        // 隐患总数
        int centerTotal = urgentMaintenanceService.getCenterNum(ids, null, null);
        // 今日隐患总数
        String today = DateUtil.getToday();
        String beginTime = today + " 00:00:00";
        String endTime = today + " 23:59:59";
        int centerNum = urgentMaintenanceService.getCenterNum(ids, beginTime, endTime);
        Map<String, Integer> map = new HashMap<>();
        map.put("today",centerNum);
        map.put("total",centerTotal);
        return CommonResult.success(map);
    }

    /**
     * 社会单位隐患排行
     */
    @AutoLog(value = "社会单位隐患排行")
    @ApiOperation(value = "社会单位隐患排行", notes = "社会单位隐患排行")
    @RequestMapping(value = "/rank", method = RequestMethod.GET)
    public CommonResult getAllUnitDangerRank(String beginTime, String endTime,long page, long limit) {

        Enterprise enterprise = getEnterprise();
        // 获取所有单位
        List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
        if (lists == null || lists.size() == 0) {
            return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
        }
        List<String> ids = new ArrayList<>();
        for (Enterprise list : lists ) {
            ids.add(list.getId() + "");
        }
        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            beginTime = beginTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
        }
        // 全部
        List<ResultVo> list = urgentMaintenanceService.getRankByDate(beginTime,endTime,ids);

        List<ResultVo> subList = list.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
        PageVo<ResultVo> pageVo = new PageVo<>();
        pageVo.setList(subList);
        pageVo.setTotalCount(list.size());
        return CommonResult.success(pageVo);

    }

    /**
     * 社会单位隐患数据对比
     */
    @AutoLog(value = "社会单位隐患数据对比")
    @ApiOperation(value = "社会单位隐患数据对比", notes = "社会单位隐患数据对比")
    @RequestMapping(value = "/dangerAvg", method = RequestMethod.GET)
    public CommonResult getDangerAvg(String beginTime, String endTime, int type, String unitId) {
        Enterprise enterprise = getEnterprise();
        // 默认
        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(unitId)) {
            String today = DateUtil.getToday();
            String year = today.substring(0, 4);
            String month = today.substring(5, 7);
            String day = today.substring(8);
            int d = Integer.parseInt(day);
            // 获取所有单位
            List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            List<String> ids = new ArrayList<>();
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
            Map<String, Object> map = new HashMap<>();
            List<ResultVo> resultVos = new ArrayList<>();
            for (int i = 1; i <= d; i++) {
                ResultVo resultVo = new ResultVo();
                String begin = "";
                String end = "";
                String date = "";
                if (i < 10) {
                    begin = year + "-" + month + "-0" + i + " 00:00:00";
                    end = year + "-" + month + "-0" + i + " 23:59:59";
                    date = year + "-" + month + "-0" + i;
                }
                else {
                    begin = year + "-" + month + "-" + i + " 00:00:00";
                    end = year + "-" + month + "-" + i + " 23:59:59";
                    date = year + "-" + month + "-" + i;
                }
                // 单日总数
                int num = urgentMaintenanceService.getAllUnitByDay(ids,begin,end);
                resultVo.setDate(date);
                resultVo.setNum(num == 0 ? 0 : (int) Math.floor(num / ids.size()));
                resultVos.add(resultVo);
            }
            map.put("all", resultVos);
            return CommonResult.success(map);

        }
        // 必须选择俩时间
        else if (StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime)) {
            return CommonResult.failed("请正确选择起始日期");
        }else if (StringUtils.isBlank(unitId) && (StringUtils.isNotBlank(beginTime) || StringUtils.isNotBlank(endTime))) {
            return CommonResult.failed("请选择单位");
        }
        // 某个单位的对比
        else {
            // 获取所有单位
            List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            List<String> ids = new ArrayList<>();
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
            String begin = beginTime + " 00:00:00";
            String end = endTime + " 23:59:59";
            Map<String, Object> map = new HashMap<>();
            // 日
            if (type == 1) {
                List<ResultVo> list = urgentMaintenanceService.getUnitByDay(begin,end,unitId);
                List<ResultVo> all = urgentMaintenanceService.getAllDay(begin,end,ids);
                List<ResultVo> unit = new ArrayList<>();
                List<ResultVo> allUnit = new ArrayList<>();
                List<String> daysBetweenDate = DateUtil.getDaysBetweenDate(beginTime, endTime);
                for (String day : daysBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    unit.add(resultVo);
                }
                for (String day : daysBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    allUnit.add(resultVo);
                }
                for (ResultVo li : list) {
                    for (ResultVo unt : unit) {
                        if (li.getDate().equals(unt.getDate())) {
                            unt.setNum(li.getNum());
                        }
                    }
                }
                for (ResultVo al : all) {
                    for (ResultVo alu : allUnit) {
                        if (al.getDate().equals(alu.getDate())) {
                            alu.setNum((int) Math.floor(al.getNum() / ids.size()));
                        }
                    }
                }
                map.put("unit", unit);
                map.put("all", allUnit);
                return CommonResult.success(map);
            }
            // 月
            else if (type == 2) {
                List<ResultVo> list = urgentMaintenanceService.getMonthByDate(begin,end,unitId);
                List<ResultVo> all = urgentMaintenanceService.getAllMonth(begin,end,ids);
                List<ResultVo> unit = new ArrayList<>();
                List<ResultVo> allUnit = new ArrayList<>();
                List<String> monthBetweenDate = DateUtil.getMonthBetweenDate(beginTime, endTime);
                for (String day : monthBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    unit.add(resultVo);
                }
                for (String day : monthBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    allUnit.add(resultVo);
                }
                for (ResultVo li : list) {
                    for (ResultVo unt : unit) {
                        if (li.getDate().equals(unt.getDate())) {
                            unt.setNum(li.getNum());
                        }
                    }
                }
                for (ResultVo al : all) {
                    for (ResultVo alu : allUnit) {
                        if (al.getDate().equals(alu.getDate())) {
                            alu.setNum((int) Math.floor(al.getNum() / ids.size()));
                        }
                    }
                }
                map.put("unit", unit);
                map.put("all", allUnit);
                return CommonResult.success(map);
            }
            // 季
            else if (type == 3) {
                List<ResultVo> list = urgentMaintenanceService.getQuarterByDate(begin,end,unitId);
                List<ResultVo> all = urgentMaintenanceService.getAllQuarter(begin,end,ids);
                List<ResultVo> unit = new ArrayList<>();
                List<ResultVo> allUnit = new ArrayList<>();
                List<String> quarterBetweenDate = DateUtil.getQuarterBetweenDate(beginTime, endTime);
                for (String day : quarterBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    unit.add(resultVo);
                }
                for (String day : quarterBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    allUnit.add(resultVo);
                }
                for (ResultVo li : list) {
                    for (ResultVo unt : unit) {
                        if (li.getDate().equals(unt.getDate())) {
                            unt.setNum(li.getNum());
                        }
                    }
                }
                for (ResultVo al : all) {
                    for (ResultVo alu : allUnit) {
                        if (al.getDate().equals(alu.getDate())) {
                            alu.setNum((int) Math.floor(al.getNum() / ids.size()));
                        }
                    }
                }
                map.put("unit", unit);
                map.put("all", allUnit);
                return CommonResult.success(map);
            }
            // 年
            else {
                List<ResultVo> list = urgentMaintenanceService.getYearByDate(beginTime,endTime,unitId);
                List<ResultVo> all = urgentMaintenanceService.getAllYear(beginTime,endTime,ids);
                List<ResultVo> unit = new ArrayList<>();
                List<ResultVo> allUnit = new ArrayList<>();
                List<String> yearBetweenDate = DateUtil.getYearBetweenDate(beginTime, endTime);
                for (String day : yearBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    unit.add(resultVo);
                }
                for (String day : yearBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    allUnit.add(resultVo);
                }
                for (ResultVo li : list) {
                    for (ResultVo unt : unit) {
                        if (li.getDate().equals(unt.getDate())) {
                            unt.setNum(li.getNum());
                        }
                    }
                }
                for (ResultVo al : all) {
                    for (ResultVo alu : allUnit) {
                        if (al.getDate().equals(alu.getDate())) {
                            alu.setNum((int) Math.floor(al.getNum() / ids.size()));
                        }
                    }
                }
                map.put("unit", unit);
                map.put("all", allUnit);
                return CommonResult.success(map);
            }
        }
    }

    /**
     * 社会单位故障恢复率
     */
    @AutoLog(value = "社会单位故障恢复率")
    @ApiOperation(value = "社会单位故障恢复率", notes = "社会单位故障恢复率")
    @RequestMapping(value = "/faultAvg", method = RequestMethod.GET)
    public CommonResult getFaultAvg(String beginTime, String endTime, int type, String unitId) {
        Enterprise enterprise = getEnterprise();
        // 默认
        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(unitId)) {
            String today = DateUtil.getToday();
            String year = today.substring(0, 4);
            String month = today.substring(5, 7);
            String day = today.substring(8);
            int d = Integer.parseInt(day);
            // 获取所有单位
            List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            List<String> ids = new ArrayList<>();
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
            HashMap<String, List<ResultVo>> map = new HashMap<>();
            List<ResultVo> resultVos = new ArrayList<>();
            for (int i = 1; i <= d; i++) {
                ResultVo resultVo = new ResultVo();
                String begin = "";
                String end = "";
                String date = "";
                if (i < 10) {
                    begin = year + "-" + month + "-0" + i + " 00:00:00";
                    end = year + "-" + month + "-0" + i + " 23:59:59";
                    date = year + "-" + month + "-0" + i;
                }
                else {
                    begin = year + "-" + month + "-" + i + " 00:00:00";
                    end = year + "-" + month + "-" + i + " 23:59:59";
                    date = year + "-" + month + "-" + i;
                }
                // 单日总数
                int count = deviceService.getAllUnitByCount(ids,begin,end,null);
                int num = deviceService.getAllUnitByCount(ids,begin,end,1);
                resultVo.setDate(date);
                resultVo.setProbability(count == 0 ? 0.00 : (double) Math.round(num * 100 /count ));
                resultVos.add(resultVo);
            }
            map.put("all", resultVos);
            return CommonResult.success(map);

        }
        // 必须选择俩时间
        else if (StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime)) {
            return CommonResult.failed("请正确选择起始日期");
        }else if (StringUtils.isBlank(unitId) && (StringUtils.isNotBlank(beginTime) || StringUtils.isNotBlank(endTime))) {
            return CommonResult.failed("请选择单位");
        }
        // 某个单位的对比
        else {
            // 获取所有单位
            List<Enterprise> lists = enterpriseService.queryUnitSelect(enterprise.getId() + "");
            if (lists == null || lists.size() == 0) {
                return CommonResult.failed("该监控中心没有任何单位或代码错误，请联系管理员");
            }
            List<String> ids = new ArrayList<>();
            for (Enterprise list : lists ) {
                ids.add(list.getId() + "");
            }
            String begin = beginTime + " 00:00:00";
            String end = endTime + " 23:59:59";
            Map<String, Object> map = new HashMap<>();
            // 日
            if (type == 1) {
                List<ResultVo> list = deviceService.getDayByDate(unitId,begin,end);
                for (ResultVo item : list) {
                    item.setProbability(item.getNum() == 0 ? 0.00 : (double) Math.round(item.getIsTrue() * 100 / item.getNum()));
                }
                List<ResultVo> all = deviceService.getAllDay(ids,begin,end);
                for (ResultVo item : all) {
                    item.setProbability(item.getNum() == 0 ? 0.00 : (double) Math.round(item.getIsTrue() * 100 / item.getNum()));
                }
                List<ResultVo> unit = new ArrayList<>();
                List<ResultVo> allUnit = new ArrayList<>();
                List<String> daysBetweenDate = DateUtil.getDaysBetweenDate(beginTime, endTime);
                for (String day : daysBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    resultVo.setIsTrue(0);
                    resultVo.setProbability(0.00);
                    unit.add(resultVo);
                }
                for (String day : daysBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    resultVo.setIsTrue(0);
                    resultVo.setProbability(0.00);
                    allUnit.add(resultVo);
                }
                for (ResultVo li : list) {
                    for (ResultVo un : unit) {
                        if (li.getDate().equals(un.getDate())) {
                            un.setNum(li.getNum());
                            un.setIsTrue(li.getIsTrue());
                            un.setProbability(li.getProbability());
                        }
                    }
                }
                for (ResultVo li : all) {
                    for (ResultVo un : allUnit) {
                        if (li.getDate().equals(un.getDate())) {
                            un.setNum(li.getNum());
                            un.setIsTrue(li.getIsTrue());
                            un.setProbability(li.getProbability());
                        }
                    }
                }
                map.put("unit", unit);
                map.put("all", allUnit);
                return CommonResult.success(map);
            }
            // 月
            else if (type == 2) {
                List<ResultVo> list = deviceService.getMonthByDate(unitId,begin,end);
                for (ResultVo item : list) {
                    item.setProbability(item.getNum() == 0 ? 0.00 : (double) Math.round(item.getIsTrue() * 100 / item.getNum()));
                }
                List<ResultVo> all = deviceService.getAllMonth(ids,begin,end);
                for (ResultVo item : all) {
                    item.setProbability(item.getNum() == 0 ? 0.00 : (double) Math.round(item.getIsTrue() * 100 / item.getNum()));
                }
                List<ResultVo> unit = new ArrayList<>();
                List<ResultVo> allUnit = new ArrayList<>();
                List<String> monthBetweenDate = DateUtil.getMonthBetweenDate(beginTime, endTime);
                for (String day : monthBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    resultVo.setIsTrue(0);
                    resultVo.setProbability(0.00);
                    unit.add(resultVo);
                }
                for (String day : monthBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    resultVo.setIsTrue(0);
                    resultVo.setProbability(0.00);
                    allUnit.add(resultVo);
                }
                for (ResultVo li : list) {
                    for (ResultVo un : unit) {
                        if (li.getDate().equals(un.getDate())) {
                            un.setNum(li.getNum());
                            un.setIsTrue(li.getIsTrue());
                            un.setProbability(li.getProbability());
                        }
                    }
                }
                for (ResultVo li : all) {
                    for (ResultVo un : allUnit) {
                        if (li.getDate().equals(un.getDate())) {
                            un.setNum(li.getNum());
                            un.setIsTrue(li.getIsTrue());
                            un.setProbability(li.getProbability());
                        }
                    }
                }
                map.put("unit", unit);
                map.put("all", allUnit);
                return CommonResult.success(map);
            }
            // 季
            else if (type == 3) {
                List<ResultVo> list = deviceService.getQuarterByDate(unitId,begin,end);
                for (ResultVo item : list) {
                    item.setProbability(item.getNum() == 0 ? 0.00 : (double) Math.round(item.getIsTrue() * 100 / item.getNum()));
                }
                List<ResultVo> all = deviceService.getAllQuarter(ids,begin,end);
                for (ResultVo item : all) {
                    item.setProbability(item.getNum() == 0 ? 0.00 : (double) Math.round(item.getIsTrue() * 100 / item.getNum()));
                }
                List<ResultVo> unit = new ArrayList<>();
                List<ResultVo> allUnit = new ArrayList<>();
                List<String> quarterBetweenDate = DateUtil.getQuarterBetweenDate(beginTime, endTime);
                for (String day : quarterBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    resultVo.setIsTrue(0);
                    resultVo.setProbability(0.00);
                    unit.add(resultVo);
                }
                for (String day : quarterBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    resultVo.setIsTrue(0);
                    resultVo.setProbability(0.00);
                    allUnit.add(resultVo);
                }
                for (ResultVo li : list) {
                    for (ResultVo un : unit) {
                        if (li.getDate().equals(un.getDate())) {
                            un.setNum(li.getNum());
                            un.setIsTrue(li.getIsTrue());
                            un.setProbability(li.getProbability());
                        }
                    }
                }
                for (ResultVo li : all) {
                    for (ResultVo un : allUnit) {
                        if (li.getDate().equals(un.getDate())) {
                            un.setNum(li.getNum());
                            un.setIsTrue(li.getIsTrue());
                            un.setProbability(li.getProbability());
                        }
                    }
                }
                map.put("unit", unit);
                map.put("all", allUnit);
                return CommonResult.success(map);
            }
            // 年
            else {
                List<ResultVo> list = deviceService.getYearByDate(unitId,begin,end);
                for (ResultVo item : list) {
                    item.setProbability(item.getNum() == 0 ? 0.00 : (double) Math.round(item.getIsTrue() * 100 / item.getNum()));
                }
                List<ResultVo> all = deviceService.getAllYear(ids,begin,end);
                for (ResultVo item : all) {
                    item.setProbability(item.getNum() == 0 ? 0.00 : (double) Math.round(item.getIsTrue() * 100 / item.getNum()));
                }
                List<ResultVo> unit = new ArrayList<>();
                List<ResultVo> allUnit = new ArrayList<>();
                List<String> yearBetweenDate = DateUtil.getYearBetweenDate(beginTime, endTime);
                for (String day : yearBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    resultVo.setIsTrue(0);
                    resultVo.setProbability(0.00);
                    unit.add(resultVo);
                }
                for (String day : yearBetweenDate) {
                    ResultVo resultVo = new ResultVo();
                    resultVo.setDate(day);
                    resultVo.setNum(0);
                    resultVo.setIsTrue(0);
                    resultVo.setProbability(0.00);
                    allUnit.add(resultVo);
                }
                for (ResultVo li : list) {
                    for (ResultVo un : unit) {
                        if (li.getDate().equals(un.getDate())) {
                            un.setNum(li.getNum());
                            un.setIsTrue(li.getIsTrue());
                            un.setProbability(li.getProbability());
                        }
                    }
                }
                for (ResultVo li : all) {
                    for (ResultVo un : allUnit) {
                        if (li.getDate().equals(un.getDate())) {
                            un.setNum(li.getNum());
                            un.setIsTrue(li.getIsTrue());
                            un.setProbability(li.getProbability());
                        }
                    }
                }
                map.put("unit", unit);
                map.put("all", allUnit);
                return CommonResult.success(map);
            }
        }
    }



}
